package com.qf.servlet;

import com.qf.utils.Constants;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @author 29125
 * @version V1.0
 * @Project java2203
 * @Package com.qf.controller
 * @Description:公共基础servlet
 * @Date 2022/5/22 22:36
 */
public class BaseServlet extends HttpServlet {


    /**
     * 所有的请求都会进入到这个方法中, 这个方法中通过反射机制来动态执行具体的业务方法
     * get请求, post请求, put请求, delete请求都会经过这个service方法
     */
    @Override
    public void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1.获取请求参数 标识符，方法名
        String methodStr = req.getParameter(Constants.TAG);
        //2.如果获取不到methodStr跳转到首页
        if (methodStr==null||"".equals(methodStr)){
            methodStr=Constants.INDEX;
        }
        //3.反射调用对应的业务逻辑方法
        Class clazz = this.getClass();//获取class类

        try {
            //从类中获取方法对象
            Method method = clazz.getMethod(methodStr, HttpServletRequest.class, HttpServletResponse.class);
            //接收执行方法的到的对象为result
            Object result= method.invoke(this,req,resp);
            //判断返回结果是否为空
            if (result!=null){
                //jump跳转到获取到的结果
                String jump= (String) result;
                //请求转发
                if (jump.startsWith(Constants.FORWARD)){
                    //获取路径
                    String path = jump.substring(jump.indexOf(Constants.FLAG) + 1);
                    req.getRequestDispatcher(path).forward(req,resp);
                }else if (jump.startsWith(Constants.REDIRECT)){
                    //重定向
                    String path = jump.substring(jump.indexOf(Constants.FLAG) + 1);
                    resp.sendRedirect(path);
                }else {
                    resp.getWriter().println(jump);
                }
            }
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }
}


